<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
		<el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="采购人" prop="purchase_staff">
                        <el-select v-model="form.purchase_staff" filterable clearable placeholder="请选择采购人" style="width:100%">
                            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="采购日期" prop="open_date">
                        <el-date-picker v-model="form.open_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入库仓库" prop="ware_id">
                        <el-select v-model="form.ware_id" filterable style="width: 100%" placeholder="仓库" @change="wareChange" clearable disabled>
                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="批量设置供应商" prop="apply_id">
                        <el-select v-model="form.apply_id" placeholder="请选择" filterable clearable @change="applyChange">
                            <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="货运方式" prop="modo">
                        <el-radio-group v-model="form.modo" class="ml-4" @change="statusChange">
                            <el-radio :label="1" size="large">空运</el-radio>
                            <el-radio :label="2" size="large">海运</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="预计到港时间" prop="port_date">
                        <el-date-picker v-model="form.port_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="入仓单号/唛头" prop="marking">
                        <el-input v-model="form.marking" placeholder="请输入入仓单号/唛头" clearable @input="marking"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
                        <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="附件" prop="enclosure">
                        <sc-upload-file v-model="form.enclosure" :limit="1">
                            <el-button type="primary" icon="el-icon-upload">选择文件</el-button>
                        </sc-upload-file>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="采购清单" prop="detail">
                <el-button type="primary" size="small" icon="el-icon-plus" @click="checkProduct">选择产品</el-button>
                <sc-form-table ref="table" v-model="form.detail" :addTemplate="addTemplate" placeholder="暂无数据" drag-sort height="400" hideAdd show-summary>
                    <el-table-column label="操作" align="center" width="50">
                        <template #default="scope">
                            <el-icon style="cursor: pointer;" color="#409eff" size="16" @click="copy(scope.row)"><el-icon-CopyDocument /></el-icon>
                        </template>
                    </el-table-column>
                    <el-table-column label="入仓单号/唛头" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.marking" placeholder="入仓单号/唛头" readonly></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="箱号" align="center" width="80">
                        <template #default="scope">
                            <el-input v-model="scope.row.box_code" placeholder="箱号" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="品类" align="center" width="120">
                        <template #default="scope">
                            {{scope.row.cate_name}}
                        </template>
                    </el-table-column>
                    <el-table-column label="产品型号" align="center" width="170">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="品名" align="center" width="170">
                        <template #default="scope">
                            {{scope.row.goods_name}}
                        </template>
                    </el-table-column> -->
                    <el-table-column label="数量" prop="one_box_number" align="center" width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.one_box_number" placeholder="数量" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="单价" align="center" width="170">
                        <template #default="scope">
                            <el-input v-model="scope.row.price" placeholder="单价" @input="totalCompute" @focus="onFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="总数量" prop="number" align="center" width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.number" placeholder="数量" readonly></el-input>
                        </template>
                    </el-table-column> -->
                    <el-table-column label="供应商" align="center" width="170">
                        <template #default="scope">
                            <el-select v-model="scope.row.apply_id" placeholder="请选择" filterable>
                                <el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-row :gutter="1">
                <el-col :span="4">
                    <el-form-item label="总金额" prop="total_price">
                        <el-input v-model="form.total_price" placeholder="总金额" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="付款账户" prop="settlement_id">
                        <el-select v-model="form.settlement_id" filterable placeholder="请选择账户" style="width:100%">
                            <el-option v-for="item in accountList" :key="item.id" :label="item.account" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="本次付款" prop="pay_price">
                        <el-input v-model="form.pay_price" placeholder="本次付款"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="运费" prop="send_money">
                        <el-input v-model="form.send_money" placeholder="运费"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="是否分期" prop="is_stages">
                        <el-switch v-model="form.is_stages" :active-value="1" :inactive-value="0" inline-prompt active-text="分期" inactive-text="不分期"></el-switch>
                        <el-tag type="primary" v-if="form.is_stages == 1" @click="openStage">设置收款金额</el-tag>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;display: flex;justify-content: flex-end;">
			<el-button @click="visible=false" >取 消</el-button>
            <!-- <sc-export-button :auth="'procure.detailsExport'" :apiObj="shopObj" :search="search" v-if="mode == 'show'"></sc-export-button> -->
			<el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
			<el-button v-if="mode == 'add'" type="primary" :loading="isSaveing" @click="submit(1)">保存并审核</el-button>
		</el-footer>
	</el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsUpdate" @closed="dialog.goods=false" :query="{system_disable:0}"></select-goods>
    <select-plan v-if="dialog.plan" ref="planDialog" @success="planUpdate" @closed="dialog.plan=false"></select-plan>
    <el-dialog title="设置分期付款" v-model="stage" :close-on-click-modal="false" :close-on-press-escape="false">
        <sc-form-table ref="table" v-model="stages_all" :addTemplate="addTemplate" placeholder="暂无数据" height="450" hideAdd hideDelete>
            <el-table-column prop="type" label="期别" align="center" width="100"></el-table-column>
            <el-table-column label="付款百分比" prop="collect_rate" align="center">
                <template #default="scope">
                    <el-input-number type="number" v-model="scope.row.collect_rate" placeholder="付款百分比" @change="stageInputRate(scope.row,scope.$index)" controls-position="right">
                        <template #suffix>
                            <span>%</span>
                        </template>
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="付款金额" prop="money" align="center">
                <template #default="scope">
                    <el-input-number type="number" v-model="scope.row.money" placeholder="付款金额" @change="stageInput(scope.row,scope.$index)" controls-position="right"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="款项日期" prop="collect_date" align="center">
                <template #default="scope">
                    <el-date-picker v-model="scope.row.collect_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%" />
                </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" align="center">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注"></el-input>
                </template>
            </el-table-column>
        </sc-form-table>
        <template #footer>
            <el-button @click="stage = false">取消</el-button>
            <el-button type="primary" @click="closeStage">确定</el-button>
        </template>
    </el-dialog>
</template>

<script>
import selectGoods from '../../goods/info/selectGoods.vue';
import SelectPlan from '../plan/selectPlan.vue';
	export default {
        components: { selectGoods, SelectPlan },
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增采购装箱单',
					copy: '新增采购装箱单',
					edit: '编辑采购装箱单',
					show: '查看采购装箱单',
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
					code: "",
					apply_id: "",
					purchase_staff: "",
					open_date: this.moment().format('YYYY-MM-DD'),
					remark: "",
					enclosure: "",
					settlement_id: "",
					pay_price: 0,
					total_price: "",
                    detail:[],
                    ware_id: "",
                    is_stages: 0,
                    stages_all: [],
                    is_check: 0,
                    modo: 1,
                    port_date :this.moment().add(10, 'days').format('YYYY-MM-DD'),
                    send_money: "",
				},
                stage: false,
                stages_all: [
                    {
                        stages_number: 1,
                        type: '首期金额',
                        collect_rate: 100,
                        money: 0,
                        collect_date: this.moment().format('YYYY-MM-DD'),
                        remark: ""
                    },
                    {
                        stages_number: 2,
                        type: '二期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 3,
                        type: '三期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 4,
                        type: '四期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 5,
                        type: '五期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 6,
                        type: '六期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 7,
                        type: '七期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 8,
                        type: '八期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 9,
                        type: '九期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 10,
                        type: '十期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 11,
                        type: '十一期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                    {
                        stages_number: 12,
                        type: '十二期金额',
                        collect_rate: 0,
                        money: 0,
                        collect_date:"",
                        remark: ""
                    },
                ],
                rules: {
					// apply_id: [
					// 	{required: true, message: '请选择供应商'}
					// ],
                    ware_id: [
						{required: true, message: '请选择仓库'}
					],
                    purchase_staff: [
						{required: true, message: '请选择采购人'}
					],
				},
                addTemplate:{},
                dialog: {
                    goods: false,
                    plan: false,
                },
                applyList: [],
                adminList: [],
                accountList: [],
                wareList: [],
			    shopObj: this.$API.procure.order.goodsLists,
                search: {code: null,},
			}
		},
		mounted() {
            this.getApply();
            this.getUser()
            this.getAccount()
            this.getWare()
            this.getMonth()
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(e){
                this.form.is_check = e
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res  = [];
                        if (this.form.id) {
                            res = await this.$API.procure.order.edit.post(this.form);
                        }else{
                            res = await this.$API.procure.order.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if(res!=''){
                            if(res.code == 1){
                                this.visible = false;
                                this.$emit('success', this.form, this.mode)
                                this.$message.success("操作成功")
                            }else{
                                this.$alert(res.message, "提示", {type: 'error'})
                            }
                        }
                    }
                })
			},
			//表单注入数据
			async setData(data){
                this.search.code = data.code
				this.form.id = data.id
                var res = await this.$API.procure.order.detail.get({id:data.id});
                this.form.code = res.data.code
                this.form.apply_id = res.data.apply_id
                this.form.ware_id = res.data.ware_id
                this.form.purchase_staff = res.data.purchase_staff
                this.form.open_date = res.data.open_date
                this.form.remark = res.data.remark
                this.form.enclosure = res.data.enclosure
                this.form.total_price = res.data.total_price
                this.form.settlement_id = res.data.settlement_id
                this.form.pay_price = res.data.pay_price
                this.form.marking = res.data.marking
                this.form.modo = res.data.modo
                this.form.port_date = res.data.port_date
                this.form.send_money = res.data.send_money
                let array = []
                res.data.detail.map(item=>{
                    array.push({
                        id:item.id,
                        goods_id:item.goods_id,
                        goods_name:item.goods && item.goods.goods_name,
                        goods_model:item.goods && item.goods.goods_model,
                        brand_name:item.goods && item.goods.brand && item.goods.brand.brand_name,
                        cate_name:item.goods && item.goods.cate && item.goods.cate.cate_name,
                        box_code:item.box_code,
                        marking:item.marking,
                        goods_spec:item.goods_spec,
                        goods_code:item.goods_code,
                        apply_id:item.apply_id,
                        box_number:item.box_number,
                        one_box_number:item.one_box_number,
                        net_weight:item.net_weight,
                        gross_weight:item.gross_weight,
                        box_spec:item.box_spec,
                        body_box:item.body_box,
                        number:item.number,
                        price:item.price,
                        total_price:item.total_price,
                        remark:item.remark,
                        ware_id:item.ware_id,
                    })
                })
                this.form.detail = array
                this.form.is_stages = res.data.is_stages
				if(res.data.is_stages == 1) {
					let stage = res.data.by_stages && res.data.by_stages
					for (let i = 0; i < stage.length; i++) {
						stage[i].type = this.stages_all[i].type
						this.stages_all.splice(i, 1, stage[i]);
					}
				}
			},
            // 选择产品
            checkProduct(){
                this.dialog.goods = true
                this.$nextTick(() => {
                    this.$refs.goodsDialog.open('add')
                })
            },
            // 选择产品返回
            goodsUpdate(data){
                let array = []
                data.map((item)=>{
                    array.push({
                        goods_id:item.id,
                        goods_name:item.goods_name,
                        goods_model:item.goods_model,
                        brand_name:item.brand && item.brand.brand_name,
                        cate_name:item.cate && item.cate.cate_name,
                        // number:1,
                        price:item.cost_price,
                        apply_id:this.form.apply_id,
                        marking:this.form.marking,
                        ware_id:this.form.ware_id,
                        remark:"",
                        // total_price:item.cost_price,
                    })
                })
                this.form.detail = [...this.form.detail,...array]
                this.totalCompute()
            },
            // 供应商列表
            async getApply(){
                var res = await this.$API.apply.apply.all.get();
                this.applyList = res.data
            },
            // 获取采购人
            async getUser(){
                var res = await this.$API.system.admin.all.get();
                this.adminList = res.data;
            },
            // 账户
            async getAccount(){
                var res = await this.$API.finance.account.all.get();
                this.accountList = res.data;
            },
            // 获取仓库
            async getWare(){
                var res = await this.$API.goods.ware.all.get();
                this.wareList = res.data;
                this.form.ware_id = 3
                // res.data.map(item => {
                //     if (item.is_default == 1) {
                //         this.form.ware_id = item.id
                //     }
                // })
            },
            onFocus(event){
                event.target.select();
            },
            totalCompute() {
                this.form.total_price = 0
                let count_price = 0
                this.form.detail.map(item => {
                    // if(item.box_number && item.one_box_number){
                    //     item.number = Number(item.box_number) * Number(item.one_box_number)
                    // }
                    item.number = item.one_box_number
                    if(item.number && item.price){
                        item.total_price = (Number(item.number) * Number(item.price)).toFixed(2)
                        count_price = Number(count_price) + (Number(item.number) * Number(item.price))
                    }
                })
                this.form.total_price = (count_price).toFixed(2)
            },
            getMonth(){
                for (let i = 1; i < this.stages_all.length; i++) {
                    let prevDate = this.moment(this.stages_all[i - 1].collect_date);
                    let nextDate = prevDate.add(1, 'month');
                    this.stages_all[i].collect_date = nextDate.format('YYYY-MM-DD');
                }
            },
            stageInput(row,index) {
                // this.setStage(row,index)
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.money
                    }
                    if(index1 == index + 1){
                        item.money = this.form.total_price - Number(num)
                    }
                })
            },
            setStage(row,index){
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.money
                    }
                    if(index1 == index + 1){
                        item.money = this.form.total_price - Number(num)
                    }
                })
            },
            stageInputRate(row,index) {
                let num = 0
                this.stages_all.map((item,index1)=>{
                    if(index1 <= index){
                        num +=item.collect_rate
                        item.money = (this.form.total_price * num / 100).toFixed(2)
                    }
                    if(index1 == index + 1){
                        item.collect_rate = 100 - Number(num)
                        // item.money = Number(this.form.total_price) * Number(item.collect_rate) / 100
                    }
                })
            },
            closeStage(){
                this.stage = false
                let array = []
                this.stages_all.map(item=>{
                    if(item.money!=0){
                        array.push({
                            collect_rate:item.collect_rate,
                            money:item.money,
                            stages_number:item.stages_number,
                            collect_date:item.collect_date,
                            remark:item.remark,
                        })
                    }
                })
                this.form.stages_all = array
            },
            openStage(){
                this.stage = true
                if(this.mode == 'add'){
                    this.stages_all[0].money = this.form.total_price
                }
            },
            applyChange(e){
                this.form.detail.map(item => item.apply_id = e)
            },
            marking(e){
                this.form.detail.map(item => item.marking = e)
            },
            statusChange(e){
                var open_date = new Date(this.form.open_date)
                if(e == 1){
                    open_date.setDate(open_date.getDate() + 10)
                }else{
                    open_date.setDate(open_date.getDate() + 45)
                }
                var y = open_date.getFullYear();
                var m = open_date.getMonth() + 1 < 10 ? "0" + (open_date.getMonth() + 1) : open_date.getMonth() + 1;
                var d = open_date.getDate() < 10 ? "0" + open_date.getDate() : open_date.getDate();
                this.form.port_date = y + "-" + m + "-" + d
            },
            wareChange(e){
                this.form.detail.map(item => item.ware_id = e)
            },
            copy(row){
                const newRow = { ...row };
                this.form.detail.push(newRow);
            },
		}
	}
</script>

<style>
</style>
